# -*- coding: utf-8 -*-
#all bullets be here

import pyglet
import math

from objects import *
import music

missile_image = pyglet.resource.image("missile.png")
batch = pyglet.graphics.Batch()

exp_imgs = [pyglet.resource.image("explo-" + str(n) + ".png") for n in xrange(1,8)]
for img in exp_imgs:
    img.anchor_x = img.width/2
    img.anchor_y = img.height/2
explosion = pyglet.image.Animation.from_image_sequence(exp_imgs, .1, False)

def do_explosion(x,y, scale=1):
    s = pyglet.sprite.Sprite(explosion, x, y, batch=batch)
    s.scale = scale
    @s.event
    def on_animation_end():
        s.delete()
    return s

class Missile(GameObject):
    def __init__(self, x, y, rot, dmg=10, vel=100):
        self.sprite = pyglet.sprite.Sprite(missile_image, x, y, batch=batch)
        self.sprite.rotation = rot
        self.damage = dmg
        self.velocity = vel
        self.life = 5
        super(Missile, self).__init__()

    def update(self, dt):
        dx = self.velocity * dt * math.sin(math.radians(self.sprite.rotation))
        dy = self.velocity * dt * math.cos(math.radians(self.sprite.rotation))
        self.sprite.x += dx
        self.sprite.y += dy
        
        #bättre sätt är uppskattat...
        self.rect = self.get_rect()
        for building in World.buildings:
            if collision(self.rect, building.rect):
                building.be_hit(self.damage)
                self.die()
        self.life -= dt
        if self.life <= 0:
            self.die()

    def die(self):
        #bättre sätt?
        try:
            World.player_bullets.remove(self)
        except ValueError:
            try:
                World.enemy_bullets.remove(self)
            except ValueError:
                print "This means something is very wrong. And jakob is too tired to fix it..."
                return
        self.sprite.delete()
        if not self.life < 0:
            music.play_sfx("explosion")
            do_explosion(self.sprite.x, self.sprite.y, .2)
